<?php
namespace app\Base\controller;

use think\Db;
use think\Request;
use wxapp\aes\WXBizDataCrypt;
use think\Controller;

class Base extends Controller
{    
    private $appid;
    private $secret;
    private $data;
    private $wxappId;

    public function __construct(){
        parent::__construct();
        $this->data        = $this->request->param();
        $this->wxappId     = $this->request->header('XX-WxappId');
       
        $wxapp_config_info = Db::name('wxapp')->where('id',$this->wxappId)->field('appid,secret')->find();
  
        $this->appid       = $wxapp_config_info['appid'];
        $this->secret      = $wxapp_config_info['secret'];
    }

    public function login()
    {   
    	$User = Db::name('user');

        //$data = $this->request->param();

        //$wxapp_id = $this->request->header('XX-WxappId');
       
        //获取小程序的appid与secret
        //$wxapp_config_info = Db::name('wxapp')->where('id',$wxapp_id)->field('appid,secret')->find();
        
        $code = $this->data['code'];
        $response = curl_get("https://api.weixin.qq.com/sns/jscode2session?appid={$this->appid}&secret={$this->secret}&js_code=$code&grant_type=authorization_code");
        $response = json_decode($response,true);

        $openid      = $response['openid'];
        $session_key = $response['session_key'];

        $token          = md5(uniqid()) . md5(uniqid());
        $current_time   = time();

        if($user_info = $User->where('openid',$openid)->where('wxapp_id',$this->wxappId)->find()){
            $user_data = [
               'session_key'     => $session_key,
               'token'           => $token,
               'last_visit_time' => $current_time,
               'visit_times'     => Db::raw('visit_times+1'),
            ];

            $User->where('id',$user_info['id'])->update($user_data);
        }else{
            $User->insert([
                'token'           => $token,
                'session_key'     => $session_key,
                'openid'          => $openid,
                'last_visit_time' => $current_time,
                'wxapp_id'        => $this->wxappId,
                'create_time'     => $current_time,
            ]);
        }
        return $token;
	}

    public function addUserInfo($user_info){
    
        $pc      = new WXBizDataCrypt($this->appid,$user_info['session_key']);
        
        $errCode = $pc->decryptData($this->data['encrypted_data'], $this->data['iv'], $wxUserData);
        
        if ($errCode != 0) {
            $this->error('操作失败!');
        }
        
        unset($wxUserData['watermark']);
        $nick_name = base64_encode($wxUserData['nickName']);
        
        $result = Db::name('user')->where('id',$user_info['id'])->update([
            'nickName'   => $nick_name,
            'avatarUrl'  => $wxUserData['avatarUrl'],
            'gender'     => $wxUserData['gender'],
            'language'   => $wxUserData['language'],
            'city'       => $wxUserData['city'],
            'province'   => $wxUserData['province'],
            'country'    => $wxUserData['country']
        ]);
        return $result;  
        
        // Db::name('user')->where('id',$this->userId)->update([
        //     'nick_name'   => $wxUserData['nickName'],
        //     'avatar_url'  => $wxUserData['avatarUrl'],
        //     'more'        => json_encode($wxUserData)
        //     ]);
        //$this->success("添加成功");
    }

	
    public function addWxappUserInfo($userId){

        $data = $this->request->param();
        
        $user_info = json_decode($data['user_info'],true);
        $result    = Db::name('user')->where('id',$userId)->update($user_info);
        
	}
}
